package com.supermarket.domain.fruit.base;

import com.supermarket.domain.strategy.NormalPriceStrategy;
import com.supermarket.domain.strategy.PriceCalculationStrategy;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 水果抽象基类（使用策略模式实现价格计算）
 */
public abstract class Fruit {
    private final String name;
    private final BigDecimal pricePerJin; // 单价（元/斤）
    private PriceCalculationStrategy calculationStrategy; // 价格计算策略

    protected Fruit(String name, BigDecimal pricePerJin, PriceCalculationStrategy strategy) {
        this.name = name;
        this.pricePerJin = pricePerJin.setScale(2, RoundingMode.HALF_UP);
        this.calculationStrategy = strategy != null ? strategy : new NormalPriceStrategy();
    }

    /**
     * 计算总价（支持策略模式）
     *
     * @param quantity 购买斤数（任意正数）
     * @return 总价格（四舍五入到分）
     */
    public BigDecimal calculatePrice(BigDecimal quantity) {
        if (quantity.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("斤数不能为负数");
        }
        return calculationStrategy.calculate(pricePerJin, quantity);
    }

    /**
     * 设置价格计算策略（支持动态切换）
     */
    public void setCalculationStrategy(PriceCalculationStrategy strategy) {
        this.calculationStrategy = strategy;
    }
}